package com.purong.purong.net;

import android.content.Context;
import android.util.Log;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;

import org.json.JSONObject;

/**
 * 网络请求类
 *
 * @author longzhiye
 */
public class HttpUtil {

    private final String TAG = "HttpUtil";

    private HttpUtil() {
    }

    private static HttpUtil httpMain;
    private static AsyncHttpClient httpClient;

    public static HttpUtil getInstance() {
        if (httpMain == null) {
            httpMain = new HttpUtil();
        }
        if (httpClient == null) {
            httpClient = new AsyncHttpClient();
            httpClient.setTimeout(15000);// 设置请求超时时间
        }
        return httpMain;
    }

    
    public void sendGet(String url, TextHttpResponseHandler jsonHttpResponseHandler) {
        httpClient.get(url, jsonHttpResponseHandler);
    }

    public void sendGet(String url, RequestParams params, TextHttpResponseHandler jsonHttpResponseHandler) {
        httpClient.get(url, params, jsonHttpResponseHandler);
    }
    
    public void sendPost(String url, TextHttpResponseHandler jsonHttpResponseHandler) {
        httpClient.post(url, jsonHttpResponseHandler);
    }

    public void sendPost(String url, RequestParams params, TextHttpResponseHandler jsonHttpResponseHandler) {
        httpClient.post(url, params, jsonHttpResponseHandler);
    }

    /**
     * 发送post请求
     *
     * @param context
     * @param url
     * @param params
     * @param responseHandler
     */
    public void sendPost(Context context, String url, JSONObject params,TextHttpResponseHandler responseHandler) {
        if (null == params) {
            params = new JSONObject();
        }
        try {
            cz.msebera.android.httpclient.entity.StringEntity stringEntity = new cz.msebera.android.httpclient.entity.StringEntity(params.toString(),"UTF-8");
            Log.d(TAG, "请求地址：" + url + "参数：" + params.toString());
            httpClient.post(context, url, stringEntity, "application/json",responseHandler);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
